package com.yzp.sort;

import java.util.Arrays;

/**
 * Description
 * 插入排序
 *
 * @className: InsertionSort
 * @author: yanzhouping
 * @date: 2019/8/15 9:54
 */
public class InsertionSort {
    public static void main(String[] args) {
        int[] arr = new int[]{1, 2, 1, 5, 3, 5, 64, 6, 9};
        arr = insertionSort(arr);
        System.out.println(Arrays.toString(arr));
    }

    /**
     * 插入排序
     *
     * @param array
     * @return
     */
    public static int[] insertionSort(int[] array) {
        if (array.length == 0) {
            return array;
        }
        int current;
        for (int i = 0; i < array.length - 1; i++) {
            current = array[i + 1];
            int preIndex = i;
            while (preIndex >= 0 && current < array[preIndex]) {
                array[preIndex + 1] = array[preIndex];
                preIndex--;
            }
            array[preIndex + 1] = current;
        }
        return array;
    }
}
